Optimization Example¶
In [1]:
from scipy.optimize import minimize
import plotly.graph_objects as go
import numpy as np
def a(x):
return x ** 2 - 4*x + 4
# plot the function
x = np.linspace(-8, 12, 100)
y = a(x)
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, mode='lines'))
fig.update_layout(width=800, height=800)
fig.show()
In [2]:
# random initial guess
guesses = np.random.uniform(-8, 12, 10)
# plot the guesses
fig.add_trace(go.Scatter(x=guesses, y=a(guesses), mode='markers', marker=dict(size=10, color='red')))
fig.show()
In [3]:
res = [minimize(a, x0, method='BFGS') for x0 in guesses]
# plot the results
fig.add_trace(go.Scatter(x=[r.x[0] for r in res], y=[r.fun for r in res], mode='markers', marker=dict(size=10, color='green')))
fig.show()
In [4]:
def b(x):
return (x-2) ** 4 + 10*np.exp(-(x-2)**2) + x
# plot the function
x = np.linspace(0, 4, 100)
y = b(x)
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, mode='lines'))
fig.update_layout(width=800, height=800)
fig.show()
In [5]:
# random initial guess
guesses = np.random.uniform(0, 4, 10)
# plot the guesses
fig.add_trace(go.Scatter(x=guesses, y=b(guesses), mode='markers', marker=dict(size=10, color='red')))
fig.show()
In [6]:
res = [minimize(b, x0, method='BFGS') for x0 in guesses]
# plot the results
fig.add_trace(go.Scatter(x=[r.x[0] for r in res], y=[r.fun for r in res], mode='markers', marker=dict(size=10, color='green')))
fig.show()
In [7]:
def c(x):
return (x[0]-2) ** 4 + 10*np.exp(-(x[0]-2)**2) + x[0] + (x[1]-2) ** 4 + 10*np.exp(-(x[1]-2)**2) + x[1]
# plot the function
x = np.linspace(0, 4, 100)
y = np.linspace(0, 4, 100)
X, Y = np.meshgrid(x, y)
Z = c([X, Y])
fig = go.Figure(go.Surface(x=X,y=Y,z=Z))
fig.update_layout(width=800, height=800)
fig.show()
In [8]:
# random initial guess
guesses = np.random.uniform(0, 4, (10, 2))
# plot the guesses
fig.add_trace(go.Scatter3d(x=guesses[:,0], y=guesses[:,1], z=c(guesses.T), mode='markers', marker=dict(size=10, color='red')))
fig.show()
In [9]:
res = [minimize(c, x0, method='BFGS') for x0 in guesses]
# plot the results
fig.add_trace(go.Scatter3d(x=[r.x[0] for r in res], y=[r.x[1] for r in res], z=[r.fun for r in res], mode='markers', marker=dict(size=10, color='green')))
fig.show()